package com.xsd.prc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description: lock锁，配合await与signal 实现线程交互
 * @Author: zhoufuzong
 * @Created: 2020-12-31 22:09:48
 * @Version: 1.1.0
 */


class AirController{

    private int number =0;

    private Lock lock =new ReentrantLock();

    private Condition condition = lock.newCondition();

    public void add(){

        lock.lock();
        try {

            // 判断
            while (number!=0){
                condition.await();
            }
            // 干活
            System.out.println(Thread.currentThread().getName()+"\t"+(++number));

            // 通知
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public void  desc(){
        lock.lock();
        try {
            // 判断
            while (number!=1){
                condition.await();
            }
            // 干活
            System.out.println(Thread.currentThread().getName()+"\t"+(--number));

            // 通知
            condition.signal();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
public class ThreadSignalDemo {

    public static void main(String[] args) {
        AirController airController =new AirController();

        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                airController.add();

            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                airController.desc();

            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                airController.add();

            }
        },"C").start();

        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                airController.desc();

            }
        },"D").start();


    }
}
